// 主JavaScript文件
const API_BASE = '/api';

// 打开游戏
function openGame(gameType) {
    const modal = document.getElementById('gameModal');
    const title = document.getElementById('gameTitle');
    const content = document.getElementById('gameContent');
    
    const games = {
        snake: { title: '贪吃蛇', file: 'snake.html' },
        whack: { title: '打地鼠', file: 'whack.html' },
        memory: { title: '记忆翻牌', file: 'memory.html' }
    };
    
    const game = games[gameType];
    title.textContent = game.title;
    
    // 加载游戏
    fetch(`games/${game.file}`)
        .then(response => response.text())
        .then(html => {
            content.innerHTML = html;
            modal.classList.remove('hidden');
            modal.classList.add('flex');
            
            // 初始化游戏
            setTimeout(() => {
                switch(gameType) {
                    case 'snake':
                        initSnake();
                        break;
                    case 'whack':
                        initWhack();
                        break;
                    case 'memory':
                        initMemory();
                        break;
                }
            }, 100);
        });
}

// 关闭游戏
function closeGame() {
    const modal = document.getElementById('gameModal');
    modal.classList.add('hidden');
    modal.classList.remove('flex');
    document.getElementById('gameContent').innerHTML = '';
}

// 加载排行榜
async function loadLeaderboard() {
    const game = document.getElementById('gameSelect').value;
    const leaderboardDiv = document.getElementById('leaderboard');
    
    try {
        const response = await fetch(`${API_BASE}/leaderboard/${game}`);
        const data = await response.json();
        
        if (data.length === 0) {
            leaderboardDiv.innerHTML = '<div class="text-center text-gray-500">暂无记录</div>';
            return;
        }
        
        let html = '<div class="space-y-2">';
        data.forEach((item, index) => {
            html += `
                <div class="leaderboard-item">
                    <span class="leaderboard-rank">#${index + 1}</span>
                    <span class="leaderboard-name">${item.name}</span>
                    <span class="leaderboard-score">${item.score}分</span>
                </div>
            `;
        });
        html += '</div>';
        
        leaderboardDiv.innerHTML = html;
    } catch (error) {
        leaderboardDiv.innerHTML = '<div class="text-center text-red-500">加载失败</div>';
    }
}

// 提交得分
async function submitScore(game, name, score) {
    try {
        const response = await fetch(`${API_BASE}/leaderboard/${game}`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ name, score })
        });
        
        if (response.ok) {
            loadLeaderboard();
            return true;
        }
        return false;
    } catch (error) {
        console.error('提交得分失败:', error);
        return false;
    }
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    loadLeaderboard();
});

// 点击模态框外部关闭
document.getElementById('gameModal').addEventListener('click', (e) => {
    if (e.target.id === 'gameModal') {
        closeGame();
    }
});
